package com.raincat.multimediapicker;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PointF;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.raincat.multimediapicker.utils.AlbumHelper;
import com.raincat.multimediapicker.utils.HorizontalListView;
import com.raincat.multimediapicker.utils.ImageCacheUtils;
import com.raincat.multimediapicker.utils.ImageController;
import com.raincat.multimediapicker.utils.ImageItem;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class LatelyImageFragment extends Fragment {
    private Context context;

    private LinearLayout ll_child;
    private TextView tv_cancel, tv_album, tv_camera, tv_original;
    private ImageView iv_original;
    private Button btn_sure;
    private HorizontalListView hl_list;

    private ListAdapter listAdapter;

    private PointF eventStart = new PointF(), eventEnd = new PointF();
    private List<ImageItem> latelyImgList = new ArrayList<>();
    private ImageCacheUtils imageCacheUtils;
    private String path = "";

    @SuppressWarnings("deprecation")
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        context = this.getActivity();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        imageCacheUtils = new ImageCacheUtils(context);

        View view = inflater.inflate(R.layout.picker_fragment_latelyimage, container, false);
        tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
        tv_album = (TextView) view.findViewById(R.id.tv_album);
        tv_camera = (TextView) view.findViewById(R.id.tv_camera);
        tv_original = (TextView) view.findViewById(R.id.tv_original);
        iv_original = (ImageView) view.findViewById(R.id.iv_original);
        btn_sure = (Button) view.findViewById(R.id.btn_sure);
        hl_list = (HorizontalListView) view.findViewById(R.id.list);
        ll_child = (LinearLayout) view.findViewById(R.id.ll_child);
        ll_child.startAnimation(AnimationUtils.loadAnimation(context, R.anim.push_bottom_in));

        setData();
        listener();
        return view;
    }

    private void setData() {
        if (!ImageController.showCameraOption) {
            tv_camera.setVisibility(View.INVISIBLE);
            tv_camera.setClickable(false);
        }
        if (!ImageController.showOriginalOption) {
            iv_original.setVisibility(View.INVISIBLE);
            tv_original.setVisibility(View.INVISIBLE);
            tv_original.setClickable(false);
        }

        latelyImgList = AlbumHelper.getInstance(context).getLatelyImage(100);
        AlbumHelper.getInstance(context).getImagesBucketList(null);
        listAdapter = new ListAdapter();
        hl_list.setAdapter(listAdapter);
        hl_list.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    return true;
                }
                return false;
            }
        });
    }

    private void listener() {
        btn_sure.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (ImageController.count != 0) {
                    if (ImageController.Mode == ImageController.TAKE) {
                        finishActivity();
                    } else if (ImageController.Mode == ImageController.CROP) {
                        ((PickerActivity) context).fragmentTabAdapter.addFragment(new ImageCropFragment(), null);
                    }
                }
            }
        });
        tv_album.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                ((PickerActivity) context).fragmentTabAdapter.addFragment(new ImageFolderFragment(), null);
            }
        });
        tv_camera.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                takePhotoByCamera();
            }
        });
        tv_original.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                ImageController.isOriginal = !ImageController.isOriginal;
                setOriginal();
            }
        });
        tv_cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                getActivity().finish();
                getActivity().overridePendingTransition(0, R.anim.push_bottom_out);
            }
        });
    }

    private void setOriginal() {
        if (iv_original != null) {
            if (!ImageController.isOriginal) {
                iv_original.setImageDrawable(null);
                tv_original.setText(context.getResources().getString(R.string.picker_original));
            } else {
                iv_original.setImageResource(R.drawable.picker_iv_enable);
                tv_original.setText(context.getResources().getString(R.string.picker_original) + ImageController.getImageSize());
            }
        }
    }

    private void setCount() {
        if (btn_sure != null) {
            if (ImageController.count == 0) {
                btn_sure.setBackgroundResource(R.drawable.picker_btn_disable);
                btn_sure.setText(context.getResources().getString(R.string.picker_OK));
            } else {
                btn_sure.setBackgroundResource(R.drawable.picker_btn_enable);
                btn_sure.setText(context.getResources().getString(R.string.picker_OK) + "(" + ImageController.count + "/" + ImageController.maxCount + ")");
            }
            if (ImageController.isOriginal)
                tv_original.setText(context.getResources().getString(R.string.picker_original) + ImageController.getImageSize());
        }
    }

    private void takePhotoByCamera() {
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        String SDPATH = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getPath();
        File file = new File(SDPATH, String.valueOf(System.currentTimeMillis()) + ".jpg");
        path = file.getPath();

        ContentValues contentValues = new ContentValues(1);
        contentValues.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
        Uri imageUri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);

        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(openCameraIntent, 250);
    }

    public void finishActivity() {
        if (ImageController.isOriginal) {
            ImageController.takeRealPathList();
            ((PickerActivity) context).finishActivity("ImageList", ImageController.realPathList);
        } else {
            ImageController.takeZoomPathList(context, new ImageController.OnAllDecodeListener() {
                @Override
                public void onResult() {
                    ImageController.takeRealPathList();
                    ((PickerActivity) context).finishActivity("ImageList", ImageController.zoomPathList);
                }
            });
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent result) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 250) {
                ImageController.addOrRemoveImageItem(context, path);
                if (ImageController.Mode == ImageController.TAKE) {
                    finishActivity();
                } else if (ImageController.Mode == ImageController.CROP) {
                    ((PickerActivity) context).fragmentTabAdapter.addFragment(new ImageCropFragment(), null);
                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
        }
    }

    private class ListAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        ListAdapter() {
            mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return latelyImgList.size();
        }

        @Override
        public Object getItem(int position) {
            return latelyImgList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            Holder holder;
            if (convertView == null) {
                holder = new Holder();
                convertView = mInflater.inflate(R.layout.picker_fragment_latelyimage_item, parent, false);
                holder.iv_img = (ImageView) convertView.findViewById(R.id.iv_img);
                holder.iv_check = (ImageView) convertView.findViewById(R.id.iv_check);
                holder.rl_check = (RelativeLayout) convertView.findViewById(R.id.rl_check);
                holder.tv_error = (TextView) convertView.findViewById(R.id.tv_error);
                holder.tv_suffix = (TextView) convertView.findViewById(R.id.tv_suffix);

                convertView.setTag(holder);
            } else
                holder = (Holder) convertView.getTag();

            final ImageItem item = latelyImgList.get(position);
            holder.iv_img.setImageBitmap(null);
            if (item.imageSuffix.equalsIgnoreCase("gif"))
                holder.tv_suffix.setVisibility(View.VISIBLE);
            else
                holder.tv_suffix.setVisibility(View.GONE);

            if (ImageController.imageItemMap.get(item.imagePath) != null) {
                holder.iv_check.setBackgroundResource(R.drawable.picker_check_enable);
                holder.iv_check.setImageResource(R.mipmap.picker_check);
            } else {
                holder.iv_check.setBackgroundResource(R.drawable.picker_check_disable);
                holder.iv_check.setImageDrawable(null);
            }

            holder.rl_check.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    View view = ((RelativeLayout) v).getChildAt(0);
                    if (ImageController.addOrRemoveImageItem(context, item)) {
                        ((ImageView) view).setImageResource(R.mipmap.picker_check);
                        view.setBackgroundResource(R.drawable.picker_check_enable);
                    } else {
                        ((ImageView) view).setImageDrawable(null);
                        view.setBackgroundResource(R.drawable.picker_check_disable);
                    }
                    setCount();
                }
            });

            holder.iv_img.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    // 截取点击事件
                    switch (event.getAction() & MotionEvent.ACTION_MASK) {
                        case MotionEvent.ACTION_DOWN:
                            eventStart.set(event.getX(), event.getY());
                            break;
                        case MotionEvent.ACTION_UP:
                            v.performClick();
                            eventEnd.set(event.getX(), event.getY());
                            if (Math.abs(eventEnd.x - eventStart.x) < 3 && Math.abs(eventEnd.y - eventStart.y) < 3) {
                                Bundle bundle = new Bundle();
                                bundle.putInt("checkIndex", position);
                                bundle.putInt("folderIndex", 0);
                                ((PickerActivity) context).fragmentTabAdapter.addFragment(new ImageVisitFragment(), bundle);
                            }
                            break;
                    }
                    return true;
                }
            });

            if (item.outHeight == 0 || item.outWidth == 0) {
                holder.iv_img.setVisibility(View.INVISIBLE);
                holder.iv_check.setVisibility(View.INVISIBLE);
                holder.tv_error.setVisibility(View.VISIBLE);
            } else if (item.outHeight == -1 || item.outWidth == -1) {
                try {
                    BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File(item.imagePath)));
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    BitmapFactory.decodeStream(in, null, options);
                    in.close();
                    if (options.outWidth < 1 || options.outHeight < 1) {
                        holder.iv_img.setVisibility(View.INVISIBLE);
                        holder.iv_check.setVisibility(View.INVISIBLE);
                        holder.tv_error.setVisibility(View.VISIBLE);
                        LayoutParams LP = holder.iv_img.getLayoutParams();
                        LP.height = (int) (146 * ((PickerActivity) context).getScale());
                        LP.width = (int) (148 * ((PickerActivity) context).getScale());
                        holder.iv_img.setLayoutParams(LP);
                    } else {
                        item.outHeight = options.outHeight;
                        item.outWidth = options.outWidth;
                        holder.iv_check.setVisibility(View.VISIBLE);
                        holder.tv_error.setVisibility(View.GONE);
                        setImage(holder.iv_img, item);
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                setImage(holder.iv_img, item);
            }

            ((ViewGroup) convertView).setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
            return convertView;
        }

        private void setImage(final ImageView img, final ImageItem item) {
            img.setVisibility(View.VISIBLE);
            LayoutParams LP = img.getLayoutParams();
            LP.height = (int) (146 * ((PickerActivity) context).getScale());
            LP.width = (int) (148 * ((PickerActivity) context).getScale() * item.outWidth / item.outHeight);
            img.setLayoutParams(LP);
            String path = imageCacheUtils.getCachePath(item.imagePath);
            if (path == null) {
                Glide.with(context).asBitmap().load(item.imagePath).into(new SimpleTarget<Bitmap>(148 * item.outWidth / item.outHeight, 146) {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        imageCacheUtils.addBitmapToFile(item.imagePath, 70, resource);
                        img.setImageBitmap(resource);
                    }
                });
            } else
                Glide.with((Activity) context).asBitmap().load(path).into(img);
        }

        class Holder {
            public ImageView iv_img, iv_check;
            public TextView tv_error, tv_suffix;
            public RelativeLayout rl_check;
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        setCount();
        setOriginal();
        if (listAdapter != null)
            listAdapter.notifyDataSetChanged();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

}
